import React, { useState, useEffect, useRef } from 'react';
import EditTable from '@/pages/EntryManage/RecruitmentManager/component/EditTable';
import { Typography, Row, Col, Tooltip } from 'antd';
import { size } from 'lodash';
import PermissionSelect from '../PermissionSelect';
import styles from './index.less';

const { Paragraph } = Typography;

// 处理业务逻辑
const resolveData = (newData, initialData) =>
    newData.map(item => {
        let obj = {
            ...item,
            companyCodeList: [],
            orgCodeList: []
        };
        if (size(initialData) > 0) {
            initialData.forEach(subItem => {
                if (subItem?.resourceModuleCode === item?.resourceModuleCode) {
                    obj = {
                        ...obj,
                        ...subItem,
                        // 后端编辑的时候详情是叫这两个字段，和提交的时候不太一样
                        orgCodeList: subItem.orgList || subItem.orgCodeList,
                        companyCodeList: subItem.companyList || subItem.companyCodeList
                    };
                }
            });
        }
        // 后端编辑的时候详情是叫这两个字段，和提交的时候不太一样
        delete obj.orgList;
        delete obj.companyList;

        return obj;
    });

// 权限管理-编辑模板-数据权限模块
const PermissionModule = React.forwardRef(({ value, onChange, selectType = 0, data }, ref) => {
    const [privateValue, setPrivateValue] = useState([]);
    const [isEmpty, setIsEmpty] = useState();
    const valueRef = useRef({
        value: [],
        defaultValue: []
    });

    useEffect(() => {
        valueRef.current.defaultValue = value || [];
    }, [value]);

    useEffect(() => {
        if (size(data) > 0) {
            setIsEmpty(false);
        } else {
            setIsEmpty(true);
        }
        valueRef.current.value = data || [];
    }, [data]);

    useEffect(() => {
        if (size(data) > 0) {
            const result = resolveData(valueRef.current.value, valueRef.current.defaultValue);
            setPrivateValue(result);

            if (onChange) {
                onChange(result);
            }
        }
    }, [data, onChange, selectType]);

    /* 权限选择同步更新
        _value：下拉选项的数据
        _type:
            1：组织机构权限
            2：行政机构权限
        _code：为空为全局统一，具体code更新具体code的数据
    */
    const handleSelectChange = (_value = {}, _type, _code) => {
        const { scopeField, scopeValues } = _value;
        const res = privateValue.map(item => {
            const obj = item;
            if (_type === 1) {
                // 组织机构权限
                if (item?.resourceModuleCode === _code) {
                    obj.organizationalScope = scopeField;
                    obj.orgCodeList = scopeValues;
                } else if (!_code) {
                    // 全局
                    obj.organizationalScope = scopeField;
                    obj.orgCodeList = scopeValues;
                }
            } else if (_type === 2) {
                if (item?.resourceModuleCode === _code) {
                    obj.administrativeScope = scopeField;
                    obj.companyCodeList = scopeValues;
                } else if (!_code) {
                    obj.administrativeScope = scopeField;
                    obj.companyCodeList = scopeValues;
                }
            }
            return obj;
        });
        setPrivateValue(res);
        if (onChange) {
            onChange(res);
        }
    };

    const scopeInitialValue = (scopeField, scopeValues, codeKey) => {
        if (isEmpty) {
            return {
                scopeField: undefined,
                scopeValues: undefined
            };
        }
        if (scopeField || scopeField === 0) {
            let tempValues = [];
            if (size(scopeValues) > 0) {
                tempValues = scopeValues.map(item => {
                    if (Object.prototype.toString.call(item) === '[object Object]') {
                        return item[codeKey];
                    }
                    return item;
                });
            }
            return {
                scopeField,
                scopeValues: tempValues
            };
        }
        return undefined;
    };

    const columns = [
        {
            title: '功能模块',
            dataIndex: 'resourceNameZh',
            width: 150,
            render: text => (
                <Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 0 }}>
                    <Tooltip title={text}>{text}</Tooltip>
                </Paragraph>
            )
        },
        {
            title: '介绍',
            dataIndex: 'remarkZh',
            width: 373,
            render: text =>
                size(text) > 0 ? (
                    <Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 0 }}>
                        <Tooltip title={text}>{text}</Tooltip>
                    </Paragraph>
                ) : (
                    '-'
                )
        },
        {
            title: '组织机构权限',
            dataIndex: 'orgCodeList',
            editable: true,
            width: 220,
            editRender: ({ record }) => (
                <PermissionSelect
                    disabled={isEmpty}
                    style={{ width: 200 }}
                    placeholder="请选择"
                    isFunctional
                    value={scopeInitialValue(record?.organizationalScope, record?.orgCodeList, 'orgCode')}
                    onChange={e => handleSelectChange(e, 1, record?.resourceModuleCode)}
                />
            )
        },
        {
            title: '行政机构权限',
            dataIndex: 'companyCodeList',
            editable: true,
            width: 220,
            editRender: ({ record }) => (
                <PermissionSelect
                    disabled={isEmpty}
                    style={{ width: 200 }}
                    placeholder="请选择"
                    value={scopeInitialValue(record?.administrativeScope, record?.companyCodeList, 'companyCode')}
                    onChange={e => handleSelectChange(e, 2, record?.resourceModuleCode)}
                />
            )
        }
    ];

    const orgInitialValue = React.useMemo(() => {
        if (isEmpty) {
            return {
                scopeField: undefined,
                scopeValues: undefined
            };
        }
        if (size(privateValue) > 0) {
            const { organizationalScope } = privateValue[0];
            let { orgCodeList } = privateValue[0];
            orgCodeList = orgCodeList?.map(item => (typeof item === 'string' ? item : item.orgCode));
            return {
                scopeField: organizationalScope,
                scopeValues: orgCodeList
            };
        }
        return undefined;
    }, [privateValue, isEmpty]);

    const compInitialValue = React.useMemo(() => {
        if (isEmpty) {
            return {
                scopeField: undefined,
                scopeValues: undefined
            };
        }
        if (size(privateValue) > 0) {
            const { administrativeScope } = privateValue[0];
            let { companyCodeList } = privateValue[0];

            companyCodeList = companyCodeList?.map(item => (typeof item === 'string' ? item : item.companyCode));
            return {
                scopeField: administrativeScope,
                scopeValues: companyCodeList
            };
        }
        return undefined;
    }, [privateValue, isEmpty]);

    return (
        <div className={styles.permissionModuleWrap} ref={ref}>
            {selectType === 0 ? (
                <Row type="flex" align="top" gutter={16}>
                    <Col
                        md={{ span: 24 }}
                        lg={{ span: 12 }}
                        xl={{ span: 9 }}
                        xxl={{ span: 7 }}
                        className={styles.unifyCol}
                    >
                        <span>组织机构权限：</span>
                        <PermissionSelect
                            disabled={isEmpty}
                            isFunctional
                            value={orgInitialValue}
                            onChange={e => handleSelectChange(e, 1)}
                            style={{ width: 200 }}
                        />
                    </Col>
                    <Col
                        md={{ span: 24 }}
                        lg={{ span: 12 }}
                        xl={{ span: 9 }}
                        xxl={{ span: 7 }}
                        className={styles.unifyCol}
                    >
                        <span>行政机构权限：</span>
                        <PermissionSelect
                            disabled={isEmpty}
                            value={compInitialValue}
                            onChange={e => handleSelectChange(e, 2)}
                            style={{ width: 200 }}
                        />
                    </Col>
                </Row>
            ) : (
                <EditTable dataSource={privateValue} columns={columns} rowKey="resourceModuleCode" />
            )}
        </div>
    );
});

export default PermissionModule;
